package cn.com.gridinfo.sooc.core.my.setting.activity;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jeremy.arad.Arad;
import com.jeremy.arad.support.picasso.CircleTransform;
import com.jeremy.arad.utils.AnimUtil;
import com.jeremy.arad.utils.Log;
import com.squareup.picasso.Picasso;

import org.apache.http.message.BasicNameValuePair;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocActivity;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.home.activity.HomeActivity;
import cn.com.gridinfo.sooc.core.login.activity.LoginActivity;
import cn.com.gridinfo.sooc.core.my.commen.CodeConst;
import cn.com.gridinfo.sooc.core.my.dao.MyDao;
import cn.com.gridinfo.sooc.core.my.personal.activity.PersonalActivity;
import cn.com.gridinfo.sooc.utils.IntentUtil;
import cn.com.gridinfo.sooc.utils.VersionUpdate;

/**
 * 设置
 * Created by 刘晓晨 on 2015/12/14.
 */
public class SettingActivity extends BaseSoocActivity {

    @InjectView(R.id.yirenzheng)
    TextView yirenzheng;// 已认证的字 （要不要显示）
    @InjectView(R.id.shimingjiantou)
    ImageView shimingjiantou;//已认证后面的箭头（要不要显示）
    @InjectView(R.id.renzhengImg)
    ImageView renzhengImg;// 已认证的图片（要不要显示）

    @InjectView(R.id.location)//节点名称
            TextView location;
    @InjectView(R.id.headimg)
    ImageView headimg;//头像
    @InjectView(R.id.name)
    TextView name;//用户名字
    private String identitytype;//拿到传来的用户类型 2 老师 3：学生  5游客
    private String userType, xm, id;//将用户类型 数字转为文字;姓名，身份证号
    NotificationManager nm;//状态栏通知管理器
    MyDao myDao;//用户dao
    private String isLogin;//用来拿到传来的是否登录的值
    private static final int INTENT_PERSON = 12;//跳转到个人信息页面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_setting);
        ButterKnife.inject(this);
        myDao = new MyDao(this);
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        identitytype = getIntent().getStringExtra("identitytype");
        xm = getIntent().getStringExtra("xm");
        id = getIntent().getStringExtra("sfzjh");
        Log.d("用户的类型是~~~~" + identitytype);
        if (identitytype.equals("2") || identitytype.equals("3")) {//用户是学生或者老师
            yirenzheng.setVisibility(View.VISIBLE);
            renzhengImg.setVisibility(View.VISIBLE);
            shimingjiantou.setVisibility(View.GONE);
        } else if (identitytype.equals("5")) {//用户不是学生，不是老师 是游客
            yirenzheng.setVisibility(View.GONE);
            renzhengImg.setVisibility(View.GONE);
            shimingjiantou.setVisibility(View.VISIBLE);
        }
        isLogin = getIntent().getStringExtra("isLogin");

        //显示目前登陆的节点，（在最下方）
        location.setText(Arad.preferences.getString(LocalMark.SERVER_NAME.getName()));
        Picasso.with(this).load(getIntent().getStringExtra("imgUrl")).transform(new CircleTransform()).
                error(R.mipmap.my_headimg).placeholder(R.mipmap.my_headimg).into(headimg);//加载头像
        name.setText(getIntent().getStringExtra("name"));
    }


    //个人信息点击
    @OnClick(R.id.person_rl)
    void onPersonInfoClick() {
        IntentUtil.intentSlidIn(this, PersonalActivity.class, INTENT_PERSON);
    }

    //设置标题
    @Override
    public String setupToolBarTitle() {
        return "设置";
    }

    //设置左边按钮
    @Override
    public boolean setupToolBarLeftButton(ImageView leftButton) {
        return true;
    }

    //返回
    @OnClick(R.id.toolbar_leftbtn)
    void onGoBack() {
        setResult(Activity.RESULT_CANCELED);
        finish();
    }

    // 点击修改密码
    @OnClick(R.id.changePwd_rl)
    void changePwd() {
        startActivity(new Intent(this, ChangePwdActivity.class));
        AnimUtil.intentSlidIn(this);
    }

    // 点击实名认证 返回数据
    @OnClick(R.id.shiming_rl)
    void shiming() {
        if (identitytype.equals("2") || identitytype.equals("3")) {
            //已经认证成功，直接显示
            if (identitytype.equals("2")) {
                userType = "老师";
            } else if (identitytype.equals("3")) {
                userType = "学生";
            }
            Intent intent = new Intent(this, RenzhengTypeActivity.class);
            intent.putExtra("rztype", userType);
            intent.putExtra("xm", xm);
            intent.putExtra("id", id);
            startActivity(intent);
            AnimUtil.intentSlidIn(this);
        } else {
            startActivityForResult(new Intent(this, ShiMingActivity.class), 2);
            AnimUtil.intentSlidIn(this);
        }
    }

    //更新
    @OnClick(R.id.update_rl)
    void update() {
        VersionUpdate versionUpdate = new VersionUpdate(this, false);
        versionUpdate.check();
    }

    //提现账户
    @OnClick(R.id.zhanghu_rl)
    void myAccount() {
        //请求账户信息，看是否有绑定
        startActivity(new Intent(this, ShowAccountActivity.class));
        AnimUtil.intentSlidIn(this);
    }

    /**
     * 点击 《退出登录》
     * 清空掉存入本地的信息
     */
    @OnClick(R.id.exit_login_rl)
    void exit() {
        showBasicNoTitle();
    }

    //退出弹出框
    public void showBasicNoTitle() {
        new MaterialDialog.Builder(this)
                .backgroundColor(Color.WHITE)
                .content("确定要退出吗？")
                .contentColorRes(R.color.color_666)
                .positiveText(R.string.agree).positiveColorRes(R.color.colorAccent)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        //解除绑定
//                        LoginActivity.instance.logoutAlias();
                        //清除本地信息
                        Arad.preferences.remove(LocalMark.IS_AUTO_LOGIN.getName());
                        Arad.preferences.putBoolean(LocalMark.IS_AUTO_LOGIN.getName(), false);
                        Arad.preferences.remove(LocalMark.OUATH_TOKEN.getName());
                        Arad.preferences.remove(LocalMark.OAUTH_TOKEN_SECRET.getName());
                        Arad.preferences.remove(LocalMark.USER_UID.getName());
                        Arad.preferences.remove(LocalMark.USER_IDENTITYTYPE.getName());
                        Arad.preferences.remove(LocalMark.USER_IDENTITYID.getName());
                        Arad.preferences.remove(LocalMark.USER_NICKNAME.getName());
                        Arad.preferences.remove(LocalMark.USER_REALNAME.getName());
                        Arad.preferences.remove(LocalMark.USER_EMAIL.getName());
                        Arad.preferences.remove(LocalMark.USER_SEX.getName());
                        Arad.preferences.remove(LocalMark.USER_TEL.getName());
                        Arad.preferences.remove(LocalMark.USER_SFZJH.getName());
                        Arad.preferences.flush();

                        if (HomeActivity.instance != null) {
                            HomeActivity.instance.finish();
                        }
                        IntentUtil.intentSlidIn(SettingActivity.this, LoginActivity.class, 00, new BasicNameValuePair("logOut", "logOut"));
                        finish();
                    }
                })
                .negativeText(R.string.disagree)
                .negativeColorRes(R.color.color_666)
                .show();
    }


    // 请求成功返回数据
    @Override
    public void onRequestSuccess(int requestCode) {
        super.onRequestSuccess(requestCode);
        switch (requestCode) {
            case CodeConst.MIBAOWENTI://调用忘记密码中的检测是否设置密保问题
                if (myDao.status.equals("0")) {//用户设置了密保问题
                    Intent intent = new Intent(this, YZModeActivity.class);
                    //用户绑定的手机号
                    intent.putExtra("BoundedPhoneNumber", getIntent().getStringExtra("BoundedPhoneNumber"));
                    startActivity(intent);
                    AnimUtil.intentSlidIn(this);
                } else if (myDao.status.equals("2")) {//用户没有设置密保问题
                    startActivity(new Intent(this, MiBaoActivity.class));
                    AnimUtil.intentSlidIn(this);
                }
                break;

        }


    }

    //点击 关于软件
    @OnClick(R.id.aboutApp_rl)
    void aboutApp() {
        startActivity(new Intent(this, AboutAppActivity.class));
        AnimUtil.intentSlidIn(this);
    }

    // 点击 密保问题
    @OnClick(R.id.mibaoQuestion_rl)
    void mibao() {
        String uid = Arad.preferences.getString(LocalMark.USER_UID.getName());
        myDao.mibaoQuestion(uid, uid + "0S3FV7PH8MLJT6IOAG2ECWQNXUBR1YZ459KD");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        switch (requestCode) {
            case 2://进行实名认证 ，认证成功后
                yirenzheng.setVisibility(View.VISIBLE);
                renzhengImg.setVisibility(View.VISIBLE);
                shimingjiantou.setVisibility(View.GONE);
                identitytype = data.getStringExtra("identitytype");
                xm = data.getStringExtra("xm");
                id = data.getStringExtra("id");
                Arad.preferences.putString(LocalMark.USER_IDENTITYTYPE.getName().toString(), identitytype);
                Arad.preferences.putString(LocalMark.USER_REALNAME.getName().toString(), xm);
                Arad.preferences.putString(LocalMark.USER_SFZJH.getName().toString(), id);
                Arad.preferences.flush();
                setResult(222);//传递回信息
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //从个人信息页面回来更新头像和昵称
        Picasso.with(this).load(Arad.preferences.getString(LocalMark.USER_HEADIMG.getName())).transform(new CircleTransform()).
                error(R.mipmap.my_headimg).placeholder(R.mipmap.my_headimg).into(headimg);//加载头像
        name.setText(Arad.preferences.getString(LocalMark.USER_NICKNAME.getName()));
    }
}
